package com.example.xunwuproject.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2019-03-15
 **/
@Service
public class SmsServiceImpl implements ISmsService {


    private static final Random random = new Random();

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    private static final String[] NUMS = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};


    @Override
    public ServiceResult<String> sendSms(String telephone) {
        String gapKey = "SMS::CODE::INTERVAL" + telephone;
        String result = redisTemplate.opsForValue().get(gapKey);
        if (result!=null) {
            return new ServiceResult<String>(false, "请求次数太频繁");
        }
        String code = generateRandomSmsCode();
        boolean success =true;
        if(success) {
            redisTemplate.opsForValue().set(gapKey, code, 60, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set("SMS_CODE_CONTENT_PREFIX" + telephone, code, 10, TimeUnit.MINUTES);
            return ServiceResult.of(code);
        } else {
            return new ServiceResult<String>(false, "服务忙，请稍后重试");
        }
    }

    private String generateRandomSmsCode() {
        StringBuilder sb = new StringBuilder();
        for(int i = 0;i<6;i++) {
            int index = random.nextInt(10);
            sb.append(NUMS[index]);
        }
        return sb.toString();
    }

    @Override
    public String getSmsCode(String telephone) {
        return redisTemplate.opsForValue().get("SMS_CODE_CONTENT_PREFIX"+ telephone);
    }
}

